// $Id: ExportXmlHandler.java 40 2011-09-30 13:53:58Z huijzer@gmail.com $
package lime.dql.handler;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import lime.common.LimeException;
import lime.dql.dialog.ExportXmlDialog;
import lime.dql.view.DqlResultsView;

import org.apache.commons.io.IOUtils;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.program.Program;
import org.eclipse.ui.handlers.HandlerUtil;

import com.documentum.fc.client.IDfTypedObject;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.IDfAttr;

public class ExportXmlHandler extends AbstractHandler {

	@SuppressWarnings("unchecked")
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		
		DqlResultsView view = (DqlResultsView) HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().findView(DqlResultsView.ID);
		List<IDfTypedObject> rows = (List<IDfTypedObject>) view.getViewer().getInput();
		
		ExportXmlDialog dialog = new ExportXmlDialog(HandlerUtil.getActiveShell(event));
		if (dialog.open() == Window.OK) {
			String filePath = dialog.getFilePath();
			export(rows, filePath);
		}

		return null;
	}
	
	private void export(List<IDfTypedObject> rows, String filePath) {
		
		try { 
			
			File exportFile = new File(filePath);
			FileOutputStream fileOut = new FileOutputStream(exportFile);
		
			XMLOutputFactory factory = XMLOutputFactory.newInstance();
			XMLStreamWriter writer = factory.createXMLStreamWriter(fileOut, "utf-8");
			
			writer.writeStartDocument("utf-8", "1.0");
			writer.writeStartElement("data");
			
			for (IDfTypedObject row : rows) {
				writer.writeStartElement("row");	
			
				try {
					for (int i = 0; i < row.getAttrCount(); i++) {
						IDfAttr attr = row.getAttr(i);
						String attrName = attr.getName();
						String value = row.getString(attrName);
						
						writer.writeStartElement(attrName);
						writer.writeCharacters(value);
						writer.writeEndElement();
					}				
				} catch (DfException e) {
					throw new LimeException(e);
				}
				
				writer.writeEndElement();
			}
			
			writer.writeEndElement();
			writer.writeEndDocument();
			
			writer.close();
			IOUtils.closeQuietly(fileOut);
			
			Program.launch(exportFile.getAbsolutePath());
			
		} catch (FileNotFoundException e) {
			throw new LimeException(e);
		} catch (XMLStreamException e) {
			throw new LimeException(e);
		}
		
	}

}
